﻿using Dapper;
using System.Threading.Tasks;
using Loong.EntityFrameworkCore;

namespace Loong.BackgroundJobs
{
    public class BackgroundJobDbAccessor : EfCoreDbAccessor
    {
        public BackgroundJobDbAccessor(IDbContextProvider<LoongDbContext> dbContextProvider)
            : base(dbContextProvider)
        { }

        public async Task DeleteAsync(long jobId)
        {
            string sql = "DELETE dbo.BackgroundJob WHERE Id=@Id";

            await Connection.ExecuteAsync(sql, new { Id = jobId }, Transaction);
        }

        public async Task<int> UpdateAsync(BackgroundJobInfo entity)
        {
            string sql = @"
SET NOCOUNT ON;
UPDATE [BackgroundJob] SET
[IsLocked] = @IsLocked,
[LockEndTime] = @LockEndTime,
[LastTryTime] = @LastTryTime,
[NextTryTime] = @NextTryTime,
[TryCount] = @TryCount,
[IsAbandoned] = @IsAbandoned
WHERE [Id] = @Id;
SELECT @@ROWCOUNT;
";
            return await Connection.ExecuteAsync(sql, entity, Transaction);
        }
    }
}
